#!/bin/bash
# Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

TMP_DIR="/tmp"
PROTO_DIR="/usr/local/share/protofiles"
PROTO_FILE="/var/lib/whitelist/policy"

# Extracts a field from the protobuf and unescapes it. This function takes two
# parameters: $1 is the field name without a trailing colon and $2 is the file
# where the input data is. This file must be in $TMP_DIR. The output is the
# raw unsecaped string.
function extract_protobuf_field() {
  protobuf_field=$(grep "$1:" "$TMP_DIR/$2" | \
    sed "s/^$1: \"\(.*\)\"$/\1/;s/%/%%/g")
  printf "$protobuf_field"
}

# Decodes the policy blob and prints it to the screen.
function decode_policy() {
  # Decode the wrapper protobuf.
  protoc --decode=enterprise_management.PolicyFetchResponse \
    -I "$PROTO_DIR" \
    "$PROTO_DIR/device_management_backend.proto" > \
  "$TMP_DIR/decoded_policy_response"

  # Decode the payload protobuf.
  extract_protobuf_field "policy_data" "decoded_policy_response" | \
  protoc --decode=enterprise_management.PolicyData \
    -I "$PROTO_DIR" \
    "$PROTO_DIR/device_management_backend.proto" > \
  "$TMP_DIR/policy_response_payload"

  # And the wrapped device policy data interpreted as device policy.
  extract_protobuf_field "policy_value" "policy_response_payload" | \
  protoc --decode=enterprise_management.ChromeDeviceSettingsProto \
    -I "$PROTO_DIR" \
    "$PROTO_DIR/chrome_device_policy.proto"

  rm "$TMP_DIR/decoded_policy_response" "$TMP_DIR/policy_response_payload"
}

cat "$PROTO_FILE" | decode_policy
